// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package user

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"context"
	"database/sql"
	"errors"

	"audio-server/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateApiKeyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateApiKeyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateApiKeyLogic {
	return &UpdateApiKeyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateApiKeyLogic) UpdateApiKey() (resp bool, err error) {
	id := sqlutil.GetUserId(l.ctx)
	if id <= 0 {
		return false, errors.New("用户未登录")
	}
	key, err := sqlutil.GenerateAPIKey()
	if err != nil {
		return false, errors.New("生成API密钥失败")
	}
	usersModel := model.NewUsersModel(l.svcCtx.Conn)
	user, err := usersModel.FindById(l.ctx, id)
	if err != nil || errors.Is(err, sql.ErrNoRows) {
		return false, errors.New("用户不存在")
	}
	user.ApiKey = key
	err = usersModel.Update(l.ctx, user)
	if err != nil {
		return false, errors.New("更新API密钥失败")
	}
	return true, nil
}
